package com.zone.vehicle.superapp.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;

import com.zone.sdk.module.account.entity.UserInfoEntity;
import com.zone.sdk_api.common.Content;

import org.apache.commons.lang3.ObjectUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SharedPreferencesUtil<T> {

    public static final String TAG = SharedPreferencesUtil.class.getSimpleName();
    // 创建一个写入器
    private static SharedPreferences mPreferences;
    private static SharedPreferences.Editor mEditor;
    private static SharedPreferencesUtil mSharedPreferencesUtil;

    // 构造方法
    @SuppressLint("CommitPrefEdits")
    private SharedPreferencesUtil(Context context) {
        mPreferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();
    }

    public static SharedPreferencesUtil getInstance(Context context) {
        if (mSharedPreferencesUtil == null) {
            mSharedPreferencesUtil = new SharedPreferencesUtil(context);
        }
        return mSharedPreferencesUtil;
    }
    // 单例模式
//    public static SharedPreferencesUtil getInstance(Context context) {
//        if (mSharedPreferencesUtil == null) {
//            mSharedPreferencesUtil = new SharedPreferencesUtil(context);
//        }
//        return mSharedPreferencesUtil;
//    }

    // 存入数据
    public void putSP(String key, String value) {
        mEditor.putString(key, value);
        mEditor.commit();
    }

    // 获取数据
    public String getSP(String key) {
        return mPreferences.getString(key, "");
    }

    public void setBoolean(String key, boolean value) {
        mEditor.putBoolean(key, value);
        mEditor.commit();
    }
    // 获取数据
    public boolean getBoolean(String key, boolean defaultValue) {
        return mPreferences.getBoolean(key, defaultValue);
    }

    // 移除数据
    public void removeSP(String key) {
        mEditor.remove(key);
        mEditor.commit();
    }

    /**
     * 针对复杂类型存储
     *
     * @param key
     * @param object
     */

    public void setObject(String key, Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(baos);

            out.writeObject(object);

            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));

            mEditor.putString(key, objectVal);

            mEditor.commit();

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                baos.close();

                if (out != null) {
                    out.close();

                }

            } catch (IOException e) {
                e.printStackTrace();

            }

        }

    }

    public String getUserId(Context context) {
        Object o = SharedPreferencesUtil.getInstance(context).getObject(Content.USER_INFO, UserInfoEntity.class);
        if (ObjectUtils.isEmpty(o)) {
            Log.w(TAG, "build user entity error of null user info ");
            return null;
        }
        UserInfoEntity userInfoEntity = (UserInfoEntity) o;
        return String.valueOf(userInfoEntity.getId());
    }

    @SuppressWarnings("unchecked")

    public T getObject(String key, Class clazz) {
        if (mPreferences.contains(key)) {
            String objectVal = mPreferences.getString(key, null);

            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);

            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);

            ObjectInputStream ois = null;

            try {
                ois = new ObjectInputStream(bais);

                T t = (T) ois.readObject();

                return t;

            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();

            } finally {
                try {
                    bais.close();

                    if (ois != null) {
                        ois.close();

                    }

                } catch (IOException e) {
                    e.printStackTrace();

                }

            }

        }

        return null;

    }

    /**
     * 对于外部不可见的过渡方法
     *
     * @param key
     * @param clazz
     * @param sp
     * @return
     */

    @SuppressWarnings("unchecked")

    private T getValue(String key, Class clazz, SharedPreferences sp) {
        T t;

        try {
            t = (T) clazz.newInstance();

            if (t instanceof Integer) {
                return (T) Integer.valueOf(sp.getInt(key, 0));

            } else if (t instanceof String) {
                return (T) sp.getString(key, "");

            } else if (t instanceof Boolean) {
                return (T) Boolean.valueOf(sp.getBoolean(key, false));
            } else if (t instanceof Long) {
                return (T) Long.valueOf(sp.getLong(key, 0L));
            } else if (t instanceof Float) {
                return (T) Float.valueOf(sp.getFloat(key, 0L));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
            Log.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            Log.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        }
        Log.e("system", "无法找到" + key + "对应的值");
        return null;

    }
}